import requests
import binascii
import cv2
import numpy as np

# 获取token
def get_token(apikey, secretkey):
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + apikey + '&client_secret=' + secretkey
    response = requests.get(url)
    if response:
        return response.json()["access_token"]
       
# 调用百度人脸搜索API
def search_face(face, token):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
    # 将采集到的图片编码为base64字符串
    base64 = binascii.b2a_base64(face)
    # 构造API参数
    params = {
        "image": base64.decode(),
        "image_type":"BASE64",
        "group_id_list":"class_1"
        }
    request_url = request_url + "?access_token=" + token
    headers = {'content-type': 'application/json'}
    # 发送HTTP请求
    response = requests.post(request_url, json=params, headers=headers)
    if response:
        # 打印匹配的人脸ID
        print (response.json()["result"]["user_list"][0]["user_id"])


token = get_token("自己的APIKEY", "自己的SECRETKEY")
cam = cv2.VideoCapture(0)
snapshot = cam.read()[1]
jpg = cv2.imencode(".jpg", snapshot)[1]
image = np.array(jpg).tobytes()
search_face(image, token)
cam.release()
